using System;
using System.Xml;

namespace DaphneTranslator.BusinessLogic
{
	/// <summary>
	/// Xml saver - saver to XML.
	/// </summary>
	public class XmlSaver: ISaver
	{
		private string keyNodeDictionary = "Dictionary";
		private string keyAttrCulture = "Culture";
		private string keyNodeText = "Value";
		private string keyAttrId = "Id";
		private string keyAttrEnglishName = "EnglishName";
		private string keyAttrCultureName = "CultureName";
			
		private XmlDocument _doc;
		
		public XmlSaver ()
		{
		}

		#region ISaver implementation
		
		/// <summary>
		/// Save the specified sFilePath and data.
		/// </summary>
		public void Save (string sFilePath, LanguageFile data)
		{
			// create document		
			_doc = new XmlDocument ();
			
			XmlDeclaration decl = _doc.CreateXmlDeclaration ("1.0", "utf-8", null);
			_doc.AppendChild (decl);
			
			// create root object
			XmlElement root = AddElement (keyNodeDictionary, null);
			_doc.AppendChild (root);
			AddAttribute (root, keyAttrCulture, data.Culture);
			AddAttribute(root, keyAttrEnglishName, data.EnglishName);
			AddAttribute(root, keyAttrCultureName, data.CultureName);
			
			// iterate through texts and create XML nodes
			foreach (LanguageText text in data.Texts) {
				XmlElement textElement = AddElement (keyNodeText, root);
				AddAttribute (textElement, keyAttrId, text.Key);
				AddAttribute (textElement, text.ValueXmlKey, text.Value);									
			}
			
			_doc.Save (sFilePath);		
		}
		
		/// <summary>
		/// Adds the element.
		/// </summary>
		private  XmlElement AddElement (string sName, XmlElement parent)
		{
			XmlElement element = _doc.CreateElement (sName);
			if(parent != null)
				parent.AppendChild (element);		
			return element;
		}
		
		/// <summary>
		/// Adds the attribute.
		/// </summary>
		private void AddAttribute (XmlNode node, string sAttrName, string sAttrValue)
		{
			XmlAttribute attribute = _doc.CreateAttribute (sAttrName);
			attribute.Value = sAttrValue;
			node.Attributes.Append (attribute);
		}
		
		#endregion
	}
}

